package main

import (
	"net/http"
	"fmt"
	"os"
	"io/ioutil"
	"strings"
	"regexp"
	"log"
	"net/url"
	"flag"
)

var img_dir string
var img_url string

func main() {
	u := flag.String("url","http://wuxianfuli.cc/pic?paged=%d","图片地址")
	dir := flag.String("dir","D://img/","图片保存目录")
	first_page := flag.Int("fp",1,"第一页")
	max_page := flag.Int("mp",1,"最大页")
	flag.Parse()
	img_url = *u
	img_dir = *dir
	log.Println("dir\t",img_dir)
	log.Println("url\t",img_url)
	log.Println("fp\t",*first_page)
	log.Println("mp\t",*max_page)
	for a := *first_page; a <= *max_page; a++ {
		getImg(a)
	}
}

//获取图片地址
func getImg(paged int) {
	the_url := fmt.Sprintf(img_url, paged)
	log.Println(the_url)
	if resp, err := http.Get(the_url); err == nil {
		b, err := ioutil.ReadAll(resp.Body)
		resp.Body.Close()
		if err != nil {
			fmt.Fprintf(os.Stderr, "fetch: reading %s: %v\n", the_url, err)
			return
		}
		//<p><img src="http://wx3.sinaimg.cn/mw600/006l0mbogy1fj13l6r0tlj30u011idle.jpg" /></p>
		reg := regexp.MustCompile("<p><img src=\".+\\.(jpeg|bmp|png|ico|jpg|gif)\" /></p>")
		bb := reg.FindAll(b, -1)
		for _, v := range bb {
			s := string(v)
			ss := strings.Split(s, "\"")
			if len(ss) < 2 {
				log.Println(string(b), "\t\t", len(ss))
			} else {
				//log.Println(s)
				log.Println("将下载图片:",ss[1])
				saveImages(ss[1])
			}
		}
	}
}

//下载图片
func saveImages(img_url string) {
	//log.Println(img_url)
	u, err := url.Parse(img_url)
	if err != nil {
		log.Println("解析图片失败:", img_url, err)
		return
	}

	//去掉最左边的'/'
	tmp := strings.TrimLeft(u.Path, "/")
	filename := img_dir + strings.ToLower(strings.Replace(tmp, "/", "-", -1))

	exists := checkExists(filename)
	if exists {
		log.Println("图片已经存在")
		return
	}

	response, err := http.Get(img_url)
	if err != nil {
		log.Println("get img_url failed:", err)
		return
	}

	defer response.Body.Close()

	data, err := ioutil.ReadAll(response.Body)
	if err != nil {
		log.Println("read data failed:", img_url, err)
		return
	}

	image, err := os.Create(filename)
	if err != nil {
		log.Println("create file failed:", filename, err)
		return
	}

	defer image.Close()
	image.Write(data)
}

func checkExists(filename string) bool {
	_, err := os.Stat(filename)
	return err == nil
}
